package com.tenton.netty.tcp;

import com.tenton.netty.config.NettyConfig;
import com.tenton.netty.pool.ThreadPool;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @ClassName： TcpServer
 * @Description：
 * @Author： tangdong
 * @Date： 2024/7/19 17:09
 */
@Component
@Slf4j
public class TcpServer implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        ThreadPool.dataDealThreadPool.execute(() -> {
            TcpServer.start(new NioEventLoopGroup(), new NioEventLoopGroup(), NettyConfig.tcpPubPort);
        });
    }

    /**
     * TCP服务启动
     *
     * @param bossGroup
     * @param workGroup
     * @param port      端口
     */
    private static void start(EventLoopGroup bossGroup, EventLoopGroup workGroup, Integer port) {
        try {
            final ServerBootstrap bootstrap = new ServerBootstrap();
            /**
             * 设置相关参数
             */
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new TcpServerHandler());
                        }
                    });
            /**
             * 启动服务端，绑定端口
             */
            final ChannelFuture channelFuture = bootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        } finally {
            //优雅关闭组
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void sendMessage(byte[] data){
        if (TcpServerHandler.channelGroup.isEmpty()){
            log.error("TCP服务端无客户端连接！");
            return;
        }
        TcpServerHandler.channelGroup.writeAndFlush(Unpooled.copiedBuffer(data));
        log.info("TCP数据发送成功！");
    }
}
